<template>
  <el-dialog
    title="商户钱包流水"
    :visible.sync="dialogVisible"
    width="900px"
    :close-on-click-modal="false"
    @open="handleOpen"
    @closed="handleClosed">
    
    <!-- 商户信息头部 -->
    <div class="merchant-header" v-if="merchantData">
      <div class="merchant-info">
        <el-avatar :size="50" :src="merchantData.avatar || ''">
          {{ merchantData.name.charAt(0) }}
        </el-avatar>
        <div class="merchant-details">
          <div class="merchant-name">{{ merchantData.name }}</div>
          <div class="merchant-mobile">{{ merchantData.mobile }}</div>
        </div>
      </div>
      <div class="balance-display">
        <div class="balance-label">当前余额</div>
        <div class="balance-amount">¥{{ formatAmount(merchantData.balance || 0) }}</div>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="交易类型">
          <el-select 
            v-model="filterForm.transaction_type" 
            clearable 
            placeholder="请选择" 
            style="width: 120px;">
            <el-option label="充值" :value="1"></el-option>
            <el-option label="消费" :value="2"></el-option>
            <el-option label="退款" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 240px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="loadData">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 流水统计 -->
    <div class="wallet-stats" v-if="stats">
      <el-row :gutter="15">
        <el-col :span="8">
          <div class="stat-item recharge">
            <div class="stat-icon">
              <i class="el-icon-plus"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ formatAmount(stats.total_recharge) }}</div>
              <div class="stat-label">总充值 ({{ stats.recharge_count }}笔)</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-item consume">
            <div class="stat-icon">
              <i class="el-icon-minus"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ formatAmount(stats.total_consume) }}</div>
              <div class="stat-label">总消费 ({{ stats.consume_count }}笔)</div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-item refund">
            <div class="stat-icon">
              <i class="el-icon-refresh-left"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ formatAmount(stats.total_refund) }}</div>
              <div class="stat-label">总退款 ({{ stats.refund_count }}笔)</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 流水列表 -->
    <div class="wallet-table">
      <el-table 
        :data="walletData" 
        v-loading="loading" 
        style="width: 100%;"
        :max-height="400">
        <el-table-column prop="id" label="流水ID" width="80" align="center"></el-table-column>
        
        <el-table-column label="交易类型" width="100" align="center">
          <template slot-scope="{row}">
            <el-tag :type="getTransactionTypeColor(row.transaction_type)" size="small">
              {{ getTransactionTypeText(row.transaction_type) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="交易金额" width="130" align="right">
          <template slot-scope="{row}">
            <span :class="getAmountClass(row.amount)">
              {{ row.amount > 0 ? '+' : '' }}¥{{ formatAmount(Math.abs(row.amount)) }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column label="余额" width="130" align="right">
          <template slot-scope="{row}">
            <span class="balance-text">¥{{ formatAmount(row.balance_after) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="remark" label="备注" show-overflow-tooltip>
          <template slot-scope="{row}">
            <span>{{ row.remark || '-' }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="交易时间" width="160">
          <template slot-scope="{row}">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="{row}">
            <el-button 
              type="text" 
              size="small" 
              @click="showTransactionDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 底部操作 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button type="primary" @click="exportWalletData" :loading="exportLoading">
        <i class="el-icon-download"></i>
        导出流水
      </el-button>
    </div>

    <!-- 交易详情弹窗 -->
    <el-dialog
      title="交易详情"
      :visible.sync="detailVisible"
      width="500px"
      append-to-body
      :close-on-click-modal="false">
      <div v-if="currentTransaction">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="流水ID">{{ currentTransaction.id }}</el-descriptions-item>
          <el-descriptions-item label="交易类型">
            <el-tag :type="getTransactionTypeColor(currentTransaction.transaction_type)" size="small">
              {{ getTransactionTypeText(currentTransaction.transaction_type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="交易金额">
            <span :class="getAmountClass(currentTransaction.amount)">
              {{ currentTransaction.amount > 0 ? '+' : '' }}¥{{ formatAmount(Math.abs(currentTransaction.amount)) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="交易前余额">
            ¥{{ formatAmount(currentTransaction.balance_before || 0) }}
          </el-descriptions-item>
          <el-descriptions-item label="交易后余额">
            ¥{{ formatAmount(currentTransaction.balance_after) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注信息">
            {{ currentTransaction.remark || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="交易时间">
            {{ formatDate(currentTransaction.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="操作员" v-if="currentTransaction.operator_name">
            {{ currentTransaction.operator_name }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { getMerchantWallet, getMerchantWalletStats, exportMerchantWalletData } from '@/api/chuandao';

export default {
  name: 'MerchantWalletDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    merchantData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      exportLoading: false,
      detailVisible: false,
      
      // 筛选条件
      filterForm: {
        transaction_type: null
      },
      dateRange: null,
      
      // 分页数据
      page: 1,
      limit: 20,
      total: 0,
      
      // 流水数据
      walletData: [],
      stats: null,
      currentTransaction: null
    };
  },

  watch: {
    visible(val) {
      this.dialogVisible = val;
    },
    dialogVisible(val) {
      this.$emit('update:visible', val);
    }
  },

  methods: {
    // 弹窗打开
    handleOpen() {
      this.resetFilter();
      this.loadData();  // loadData() 内部会调用 loadStats()，无需重复调用
    },

    // 弹窗关闭
    handleClosed() {
      this.resetData();
    },

    // 重置数据
    resetData() {
      this.walletData = [];
      this.stats = null;
      this.page = 1;
      this.total = 0;
      this.loading = false;
    },

    // 重置筛选条件
    resetFilter() {
      this.filterForm = {
        transaction_type: null
      };
      this.dateRange = null;
      this.page = 1;
      this.loadData(); // 重置后自动加载全部数据，提升用户体验
    },

    // 加载流水数据
    loadData() {
      if (!this.merchantData || !this.merchantData.id) return;

      this.loading = true;
      const params = {
        page: this.page,
        limit: this.limit,
        transaction_type: this.filterForm.transaction_type
      };

      // 添加日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        params.start_date = this.dateRange[0];
        params.end_date = this.dateRange[1];
      }

      getMerchantWallet(this.merchantData.id, params).then(res => {
        if (res.code === 0) {  // 修改为0，符合ele-pro-table规范
          this.walletData = res.data.list || [];
          this.total = res.data.total || 0;
          // 同时刷新统计数据，保持数据一致性
          this.loadStats();
        } else {
          this.$message.error(res.message || '获取流水失败');
        }
      }).catch(error => {
        console.error('获取钱包流水失败:', error);
        this.$message.error('获取流水失败，请重试');
      }).finally(() => {
        this.loading = false;
      });
    },

    // 加载统计数据
    loadStats() {
      if (!this.merchantData || !this.merchantData.id) return;

      // 构建筛选参数，与流水查询保持一致
      const params = {
        transaction_type: this.filterForm.transaction_type
      };

      // 添加日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        params.start_date = this.dateRange[0];
        params.end_date = this.dateRange[1];
      }

      // 调用真实的统计API
      getMerchantWalletStats(this.merchantData.id, params).then(res => {
        if (res.code === 0) {  // 修改为0，符合API规范
          this.stats = res.data;
        } else {
          this.$message.error(res.message || '获取统计数据失败');
          // 使用降级数据
          this.useFallbackStats();
        }
      }).catch(error => {
        console.error('获取商户统计数据失败:', error);
        this.$message.warning('统计数据加载失败，显示默认数据');
        // 使用降级数据
        this.useFallbackStats();
      });
    },

    // 降级统计数据（当API失败时使用）
    useFallbackStats() {
      this.stats = {
        total_recharge: 0.00,
        recharge_count: 0,
        total_consume: 0.00,
        consume_count: 0,
        total_refund: 0.00,
        refund_count: 0
      };
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.limit = val;
      this.page = 1;
      this.loadData();
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.page = val;
      this.loadData();
    },

    // 显示交易详情
    showTransactionDetail(row) {
      this.currentTransaction = row;
      this.detailVisible = true;
    },

    // 导出流水数据
    exportWalletData() {
      if (!this.merchantData || !this.merchantData.id) {
        this.$message.error('商户信息异常，无法导出');
        return;
      }

      this.exportLoading = true;

      // 构建导出参数，与当前筛选条件保持一致
      const params = {
        transaction_type: this.filterForm.transaction_type
      };

      // 添加日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        params.start_date = this.dateRange[0];
        params.end_date = this.dateRange[1];
      }

      exportMerchantWalletData(this.merchantData.id, params).then(res => {
        // 创建下载链接
        const blob = new Blob([res], { type: 'text/csv;charset=utf-8' });
        const downloadUrl = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = `商户钱包流水_${this.merchantData.name}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
        
        this.$message.success('导出成功');
      }).catch(error => {
        console.error('导出钱包流水失败:', error);
        this.$message.error('导出失败，请重试');
      }).finally(() => {
        this.exportLoading = false;
      });
    },

    // 获取交易类型文本
    getTransactionTypeText(type) {
      const typeMap = {
        1: '充值',
        2: '消费',
        3: '退款'
      };
      return typeMap[type] || '未知';
    },

    // 获取交易类型颜色
    getTransactionTypeColor(type) {
      const colorMap = {
        1: 'success',  // 充值
        2: 'warning',  // 消费
        3: 'info'      // 退款
      };
      return colorMap[type] || '';
    },

    // 获取金额样式类
    getAmountClass(amount) {
      if (amount > 0) {
        return 'amount-positive';
      } else if (amount < 0) {
        return 'amount-negative';
      }
      return '';
    },

    // 格式化金额
    formatAmount(amount) {
      if (amount === null || amount === undefined) return '0.00';
      return parseFloat(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      });
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '-';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }
  }
};
</script>

<style scoped>
/* 商户头部信息 */
.merchant-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  margin-bottom: 20px;
  color: white;
}

.merchant-info {
  display: flex;
  align-items: center;
}

.merchant-details {
  margin-left: 15px;
}

.merchant-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 5px;
}

.merchant-mobile {
  font-size: 14px;
  opacity: 0.9;
}

.balance-display {
  text-align: right;
}

.balance-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 5px;
}

.balance-amount {
  font-size: 24px;
  font-weight: 600;
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.filter-section .el-form {
  margin-bottom: 0;
}

/* 统计卡片 */
.wallet-stats {
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.stat-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 18px;
  color: white;
}

.stat-item.recharge .stat-icon {
  background: #67C23A;
}

.stat-item.consume .stat-icon {
  background: #E6A23C;
}

.stat-item.refund .stat-icon {
  background: #409EFF;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 3px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

/* 表格区域 */
.wallet-table {
  margin-bottom: 20px;
}

/* 金额样式 */
.amount-positive {
  color: #67C23A;
  font-weight: 500;
}

.amount-negative {
  color: #F56C6C;
  font-weight: 500;
}

.balance-text {
  color: #E6A23C;
  font-weight: 500;
}

/* 分页样式 */
.pagination-wrapper {
  text-align: center;
  margin-top: 20px;
}

/* 底部操作 */
.dialog-footer {
  text-align: right;
}

/* 表格操作按钮 */
.el-button--text {
  padding: 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .merchant-header {
    flex-direction: column;
    text-align: center;
  }

  .merchant-info {
    margin-bottom: 15px;
  }

  .balance-display {
    text-align: center;
  }

  .filter-section .el-form {
    text-align: center;
  }

  .filter-section .el-form-item {
    display: block;
    margin-bottom: 15px;
  }

  .wallet-stats .el-col {
    margin-bottom: 15px;
  }
}

/* 弹窗内部样式调整 */
.el-dialog__body {
  padding: 20px;
}

/* 嵌套弹窗样式 */
.el-dialog__wrapper .el-dialog {
  margin-top: 8vh;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
}

/* 描述列表样式 */
.el-descriptions {
  margin-bottom: 0;
}

/* 表单样式 */
.el-form-item {
  margin-bottom: 15px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}
</style>